#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string svr_ip = argv[1];
    uint16_t svr_port = atoi(argv[2]);

    // 1 创建socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket creat fail" << std::endl;
        return 2;
    }
    // 2 client不用显示bind、listen、accept
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    server.sin_port = htons(svr_port);
    // connect
    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cerr << "socket connect fail" << std::endl;
        return 2;
    }
    std::cout<<"connect success"<<std::endl;

    //进行服务请求
    while (true)
    {
        std::cout << "please enter:";
        char buffer[1024];
        fgets(buffer, sizeof(buffer) - 1, stdin);
        write(sock, buffer, strlen(buffer));
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}
